<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目编号" prop="code">
        <el-input
            v-model="queryParams.code"
            placeholder="请输入项目编号"
            clearable
            @keyup.enter="handleQuery"
            style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目负责人" prop="projectLeader" label-width="100">
        <el-input
            v-model="queryParams.projectLeader"
            placeholder="请输入项目负责人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目联系人" prop="projectContact">
        <el-input
            v-model="queryParams.projectContact"
            placeholder="请输入项目联系人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="签订时间" prop="signingTime">
        <el-date-picker clearable
                        v-model="queryParams.signingTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择签订时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结题时间" prop="conpletionTime">
        <el-date-picker clearable
                        v-model="queryParams.conpletionTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择结题时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="项目归属" prop="projectOwner">
        <el-input
            v-model="queryParams.projectOwner"
            placeholder="请输入项目归属"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs v-model="activeFinish" @tab-click="handleFinishClick">
      <el-tab-pane label="未结题" name="first"></el-tab-pane>
      <el-tab-pane label="已结题" name="second"></el-tab-pane>
    </el-tabs>
    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目编号" fixed align="center" prop="code" width="200"/>
      <el-table-column label="合同编号" align="center" prop="contractCode" width="220" />
      <el-table-column label="项目负责人" align="center" prop="projectLeader" width="150" />
      <el-table-column label="项目联系人" align="center" prop="projectContact" width="150" />
      <el-table-column label="项目名称" align="center" prop="projectName" width="400"/>
      <el-table-column label="合同总额" align="center" prop="totalAmount" width="120">
        <template #default="scope">
          <span>{{ scope.row.totalAmount/10000 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同签订时间" align="center" prop="signingTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.signingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="中期检查时间" align="center" prop="inspectionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.inspectionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结题时间" align="center" prop="conpletionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.conpletionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款批次" align="center" width="120">
        <template #default="scope">
          <el-button link @click="showPayments(scope.row.projectId)" type="primary">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="项目归属" align="center" prop="projectOwner" width="200" />
      <el-table-column v-if="activeFinish=='first'" label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" >修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDeleteOne(scope.row.projectId)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body style="border-radius: 20px;padding-right: 20px" class="larger-input">
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合同编号" style="margin-left: 20px">
          <el-select
              v-model="form.contractCode"
              @change="handleSelectChange"
              filterable
              placeholder="Select"
              style="width: 800px;"
          >
            <el-option
                v-for="item in contractList"
                :key="item.contractCode"
                :label="item.contractCode"
                :value="item.contractCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName" style="margin-left: 20px">
          <el-input
              disabled
              v-model="form.projectName"
              placeholder="请输入项目名称"
          >
            <template #prepend>
              <el-select v-model="form.type" placeholder="Select" style="width: 115px">
                <el-option label="HT" value="HT" />
                <el-option label="SY" value="SY" />
                <el-option label="TZ" value="TZ" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="项目负责人" prop="projectLeaderId" label-width="100">
          <el-select
              v-model="form.projectLeaderId"
              filterable
              placeholder="Select"
              style="width: 800px"
          >
            <el-option
                v-for="item in leaderList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目联系人" prop="projectContact">
          <el-input
              v-model="form.projectContact"
              placeholder="请输入项目联系人"
          />
        </el-form-item>
        <el-form-item label="检查时间" prop="inspectionTime" style="margin-left: 20px">
          <el-date-picker clearable
                          v-model="form.inspectionTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择检查时间"
                          style="width: 800px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结题时间" prop="conpletionTime" style="margin-left: 20px">
          <el-date-picker clearable
                          v-model="form.conpletionTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择结题时间"
                          style="width: 800px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目归属" prop="projectOwner" style="margin-left: 20px">
          <el-input v-model="form.projectOwner" placeholder="请输入项目归属" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="付款批次" v-model="showp" width="800px" append-to-body style="border-radius:20px;">
      <div style="display: flex; justify-content: space-between; margin: 18px;">
        <span style="font-size: 18px;margin-left: 18px"> 合同总额：{{(payment.hasPay+payment.unPay)/100}} 元</span><br/>
        <br>
        <span style="font-size: 18px">已回款金额：{{(payment.hasPay)/100}} 元</span><br/>
        <br>
        <span style="font-size: 18px">待回款金额：{{(payment.unPay)/100}} 元</span><br/>
        <br>
      </div>
      <el-table :data="payment.pay" >
        <el-table-column label="回款日期" prop="paymentDate"/>
        <el-table-column label="金额（元）" prop="paymentPrice">
          <template #default="scope">
            {{scope.row.paymentPrice/100}}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="dProject">
import {
  listProject,
  getProject,
  delProject,
  updateProject,
  listContract,
  listLeader,
  insertProject
} from "@/api/project/project";
import {parseTime} from "@/utils/ruoyi.js";
import {getByPid} from "@/api/finance/finance.js";

const { proxy } = getCurrentInstance();

const projectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const activeFinish=ref('first');
const data = reactive({
  form: {
    contract:{}
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    projectName: null,
    conpletionTime: null,
    projectOwner: null,
    signingTime: null,
    totalAmount:null,
    projectLeader:null
  },
  rules: {
    contractCode:[
      {required: true,message: '请选择合同编号',trigger:'change'}
    ],
    projectName:[
      {required: true,message:'请输入项目名称', trigger:'blur'}
    ],
    projectLeaderId:[
      {required: true,message:'请选择项目负责人',trigger:'change'}
    ],
    projectOwner:[
      {required: true,message:'请输入项目归属',trigger:'blur'}
    ],
    haveContract:[
      {required: true,message:'请选择项目类型',trigger:'blur'}
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function handleFinishClick(tab){
  if (tab.paneName=='second'){
    queryParams.value.finish=true;
  }else {
    queryParams.value.finish=false;
  }
  getList();
}
/** 查询项目列表 */
function getList() {
  loading.value = true;
  listProject(queryParams.value).then(response => {
    projectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    projectId: null,
    contractCode: null,
    code: null,
    projectName: null,
    projectLeaderId: null,
    inspectionTime: null,
    conpletionTime: null,
    projectOwner: null,
    projectStyle: null,
    haveContract: null,
    contractName: null,
    signingTime: null,
    totalAmount: null,
    contract:{}
  };
  proxy.resetForm("projectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.projectId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getContract();
  getLeader();
  open.value = true;
  // xg.value=false;
  title.value = "添加项目";
  form.value.isAdd=true;
}
// const xg=ref(true);
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _projectId = row.projectId || ids.value
  getLeader();
  getProject(_projectId).then(response => {
    form.value = response.data;
    open.value = true;
    // xg.value=true;
    title.value = "修改项目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectRef"].validate(valid => {
    if (valid) {
      if (form.value.isAdd) {
        insertProject(form.value).then(response => {
          proxy.$modal.msgSuccess("添加成功");
          open.value = false;
          getList();
        });
      }else{
        updateProject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _projectIds = row.projectId || ids.value;
  proxy.$modal.confirm('是否确认删除项目编号为"' + _projectIds + '"的数据项？').then(function() {
    return delProject(_projectIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
function handleDeleteOne(id){
  const _projectIds = [id];
  proxy.$modal.confirm('是否确认删除项目编号为"' + _projectIds + '"的数据项？').then(function() {
    return delProject(_projectIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/export', {
    ...queryParams.value
  }, `project_${new Date().getTime()}.xlsx`)
}

//获取合同清单
const contractList=ref([]);
function getContract(){
  listContract().then(res=>{
    contractList.value=res.data;
    console.log(contractList.value)
  })
}
//项目负责人清单
const leaderList=ref([])
function getLeader(){
  listLeader().then(res=>{
    leaderList.value=res.data;
  })
}
//支付周期
const showp=ref(false);
const payment=ref();
function showPayments(pid){
  getByPid(pid).then(res=>{
    payment.value=res.data;
    showp.value=true;
  })
}

getList();
function handleSelectChange(value){
  for (let e of contractList.value) {
    if (e.contractCode==value){
      form.value.projectName=e.contractName;
    }
  }
}
</script>
